<template>
    <div class="tab-content">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>过去24H无人车频次</span>
                    <el-button type="primary" @click="showAddDialog">添加数据</el-button>
                </div>
            </template>
            
            <el-table :data="tableData" style="width: 100%">
                <el-table-column prop="siteName" label="站点名称"  />
                <el-table-column prop="frequency" label="无人车频次" >
                    <template #default="scope">
                        {{ scope.row.frequency }} 次/天
                    </template>
                </el-table-column>
                <el-table-column label="操作" >
                    <template #default="scope">
                        <el-button size="small" @click="editRow(scope.row, scope.$index)">编辑</el-button>
                        <el-button size="small" type="danger" @click="deleteRow(scope.$index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        
        <!-- 添加/编辑弹框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="站点名称" prop="siteName">
                    <el-input v-model="form.siteName" placeholder="请输入站点名称" />
                </el-form-item>
                <el-form-item label="无人车频次" prop="frequency">
                    <el-input-number v-model="form.frequency" placeholder="请输入无人车频次" :controls="false" :min="0" style="width: 80%" />
                    <span style="margin-left: 8px; color: #909399;">次/天</span>

                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveData">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
    import { ref, reactive } from 'vue'
    import { updateDataClassify } from '@/api/port'
    import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'

    // 表格数据类型定义
    interface TableRow {
        siteName: string
        frequency: number
    }

    // 表格数据
    const tableData = ref<TableRow[]>([])

    // 弹框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('添加数据')
    const editIndex = ref(-1)

    // 表单数据
    const form = ref<TableRow>({
        siteName: '',
        frequency: 0
    })

    // 表单验证规则
    // 数字范围验证函数
    const validateNumber = (rule: any, value: number, callback: (error?: Error) => void) => {
        if (value === null || value === undefined) {
            callback(new Error('请输入数字'))
        } else if (value < 0) {
            callback(new Error('请输入大于等于0的数字'))
        } else if (value > 1000000) {
            callback(new Error('请输入小于等于1000000的数字'))
        } else {
            callback()
        }
    }
    const rules = {
        siteName: [
            { required: true, message: '请输入站点名称', trigger: 'blur' },
            { min: 1, max: 50, message: '站点名称长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        frequency: [
            { required: true, message: '请输入无人车频次', trigger: 'blur' },
            // { type: 'number', min: 0, max: 1000000, message: '频次必须在 0 到 1000000 之间', trigger: 'blur' },
            { validator: validateNumber, trigger: 'blur' }
        ]
    }

    const formRef = ref<FormInstance>()

    // 显示添加弹框
    const showAddDialog = () => {
        dialogTitle.value = '添加数据'
        editIndex.value = -1
        form.value = {
            siteName: '',
            frequency: 0
        }
        dialogVisible.value = true
    }

    // 编辑行
    const editRow = (row: TableRow, index: number) => {
        dialogTitle.value = '编辑数据'
        editIndex.value = index
        form.value = { ...row }
        dialogVisible.value = true
    }

    // 删除行
    const deleteRow = async (index: number) => {
        try {
            await ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            tableData.value.splice(index, 1)

            await updateDataClassify({
                id: 5,
                key: 'module2',
                value: tableData.value
            })
            console.log('保存无人车频次数据:', tableData.value)
            ElMessage.success('删除成功')
        } catch {
            // 用户取消删除
        }
    }

    // 保存数据
    const saveData = async () => {
        if (!formRef.value) return
        
        try {
            await formRef.value.validate()
            
            if (editIndex.value >= 0) {
                // 编辑模式
                tableData.value[editIndex.value] = { ...form.value }
                ElMessage.success('编辑成功')
            } else {
                // 添加模式
                tableData.value.push({ ...form.value })
                ElMessage.success('添加成功')
            }
            
            dialogVisible.value = false
            
            // 保存到后端
            await updateDataClassify({
                id: 5,
                key: 'module2',
                value: tableData.value
            })
            console.log('保存无人车频次数据:', tableData.value)
            
        } catch (error) {
            ElMessage.warning('请填写完整的表单信息')
        }
    }



    // 初始化函数
    const init = (module: any) => {
        console.log(module)
        if (module && Array.isArray(module)) {
            tableData.value = module
        } else {
            tableData.value = [
                { siteName: '站点A', frequency: 25 },
                { siteName: '站点B', frequency: 18 },
                { siteName: '站点C', frequency: 32 }
            ]
        }
    }

    defineExpose({
        init
    })

</script>
<style  scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.dialog-footer {
    text-align: right;
}
</style>